from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class Customer(models.Model):
    """客户模型"""
    name = models.CharField(max_length=100, verbose_name="客户姓名")
    email = models.EmailField(blank=True, null=True, verbose_name="邮箱")
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name="电话")
    session_id = models.CharField(max_length=100, unique=True, verbose_name="会话ID")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "客户"
        verbose_name_plural = "客户"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} ({self.session_id})"


class Conversation(models.Model):
    """对话模型"""
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name="客户")
    title = models.CharField(max_length=200, verbose_name="对话标题")
    is_active = models.BooleanField(default=True, verbose_name="是否活跃")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "对话"
        verbose_name_plural = "对话"
        ordering = ['-updated_at']

    def __str__(self):
        return f"{self.customer.name} - {self.title}"


class Message(models.Model):
    """消息模型"""
    MESSAGE_TYPES = [
        ('user', '用户消息'),
        ('ai', 'AI回复'),
        ('system', '系统消息'),
    ]

    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages', verbose_name="对话")
    message_type = models.CharField(max_length=10, choices=MESSAGE_TYPES, verbose_name="消息类型")
    content = models.TextField(verbose_name="消息内容")
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name="发送时间")
    is_read = models.BooleanField(default=False, verbose_name="是否已读")

    class Meta:
        verbose_name = "消息"
        verbose_name_plural = "消息"
        ordering = ['timestamp']

    def __str__(self):
        return f"{self.get_message_type_display()}: {self.content[:50]}..."


class KnowledgeBase(models.Model):
    """知识库模型"""
    question = models.CharField(max_length=500, verbose_name="问题")
    answer = models.TextField(verbose_name="答案")
    keywords = models.CharField(max_length=200, verbose_name="关键词", help_text="用逗号分隔")
    category = models.CharField(max_length=100, verbose_name="分类")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "知识库"
        verbose_name_plural = "知识库"
        ordering = ['-updated_at']

    def __str__(self):
        return self.question
